package com.carmanage.controller;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.carmanage.domain.Page;
import com.carmanage.domain.Role;
import com.carmanage.service.RoleService;

@Controller
public class RoleController{
    
	@Resource
	private RoleService roleservice;
	
	private List<Role> roles;
	

	public RoleService getRoleservice() {
		return roleservice;
	}

	public void setRoleservice(RoleService roleservice) {
		this.roleservice = roleservice;
	}


	@RequestMapping(value ="/findAllRole")
	public String findAllRole(HttpSession session){
		roles = roleservice.findAllRole();
		session.setAttribute("ListAllRoles",roles);
		System.out.println(roles.size());
	    return "redirect:/Login.jsp";
	}
	
	@RequestMapping(value = "/findRoleFirstPage")
	public String findRoleFirstPage(HttpServletRequest request){
		int totalRows = roleservice.findAllRoleRecord();
		Page rolePage = new Page(totalRows,1); 
		request.getSession().setAttribute("RolePage",rolePage);
		 roles = roleservice.findRoleByPage(rolePage);
		 request.setAttribute("RolesByPage",roles);
		 System.out.println(roles);
		 return "forward:/pages/roleManage.jsp";   //redirect的话request传值失效
	}
	
	@RequestMapping(value = "/findRolePageBy")
	public String findRolePage(int currentPage,HttpServletRequest request){
		Page rolePage = (Page) request.getSession().getAttribute("RolePage");
		rolePage.setCurrentPage(currentPage);
		request.getSession().setAttribute("RolePage",rolePage);
		roles = roleservice.findRoleByPage(rolePage);
		request.setAttribute("RolesByPage",roles);
		return "forward:/pages/roleManage.jsp";
		
	}
	
	@RequestMapping(value = "/addRole")
	public @ResponseBody int addRole(String rolename,Date creatdate){
		int i = roleservice.addRole(rolename,creatdate);
		return i;
	}
	
	@RequestMapping(value = "/updateRole")
	public @ResponseBody  int updateRole(String actions,int roleid){
		String[] split = actions.split("a");
		List<Integer> listAction = new LinkedList<Integer>();
		for(int i=0;i<split.length;i++){
			listAction.add(Integer.parseInt(split[i]));
		}
	    int i = roleservice.updateRole(listAction,roleid);
	    return i;
	}
}
